#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : AutomaticTestProgram 
@File    : main.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/11/28 14:45 
@Describe:
"""
import time
import uvicorn
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fast_api.interface.apis import api_router
from utils.common.common_control import get_request_id
from utils.log.log_control import LogHandler

app = FastAPI()
app.include_router(api_router)
logger = LogHandler().get_logger()


@app.exception_handler(Exception)
async def exception_callback(request, err):
    """全局异常捕获"""
    base_error_message = "请求失败,请求url:{}".format(request.url)
    return JSONResponse(status_code=500,
                        content={"code": 500, "data": "{}".format(base_error_message),
                                 "message": "{}".format(err)})


@app.middleware("http")
async def log_requests(request, call_next):
    # 1、可针对 Request 或其他功能，自定义代码块
    start_time = time.time()  # 请求开始时间
    request_id = get_request_id()
    logger.info('*' * 20 + '接口请求开始,request_id:{}'.format(request_id) + '*' * 20)
    logger.info("请求路径:{}".format(request.url.path))
    logger.info("请求方式:{}".format(request.method))
    logger.info("请求IP:{}".format(request.client.host))
    logger.info("请求头信息:{}".format(request.headers))
    # 必须用 await
    response = await call_next(request)
    # 结束时间计算
    process_time = (time.time() - start_time) * 1000
    formatted_process_time = '{0:.0f}'.format(process_time)
    response.headers["X-Request-Id"] = request_id  # 响应头加上请求id方便后续排查问题
    logger.info("接口响应状态码:{}".format(response.status_code))
    logger.info("接口响应时间:{}ms".format(formatted_process_time))
    logger.info('*' * 20 + '接口请求结束,request_id:{}'.format(request_id) + '*' * 20)
    return response


if __name__ == '__main__':
    uvicorn.run(app="main:app", host='0.0.0.0', port=49, reload=True)
